<template>
  <div class="green-energy-management">
    <div class="sidebar">
      <a-menu mode="inline">
        <a-menu-item key="home" @click="currentView = 'viewProjects'">主页</a-menu-item>
        <a-menu-submenu>
          <a-menu-item key="view-projects" @click="currentView = 'viewProjects'"> 查看所有绿电项目 </a-menu-item>
          <a-menu-item key="green-energy-trade" @click="currentView = 'greenEnergyTrade'"> 绿电交易 </a-menu-item>
        </a-menu-submenu>
        <a-menu-item key="help">帮助</a-menu-item>
      </a-menu>
    </div>

    <div class="main-content">
      <a-card title="绿电管理系统" class="main-card">
        <div v-if="currentView === 'viewProjects'">
          <a-button type="primary" @click="showAddProjectModal" class="add-project-button"> 新增绿电项目 </a-button>
          <a-table
            :columns="columns"
            :data-source="projects"
            row-key="key"
            bordered
            @change="handleChange"
            class="carbon-assets-table"
            :pagination="pagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <span class="action-buttons">
                  <a @click="editProject(record)" class="edit-button">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="deleteProject(record)" class="delete-button">删除</a>
                </span>
              </template>
            </template>
          </a-table>
        </div>

        <a-modal title="新增绿电项目" v-model:visible="isAddProjectModalVisible" @cancel="cancelAddProject" @ok="submitNewProject">
          <a-form :model="newProject" layout="vertical">
            <a-form-item label="项目名称">
              <a-input v-model:value="newProject.projectName" placeholder="请输入项目名称" />
            </a-form-item>
            <a-form-item label="碳资产类型">
              <a-select
                v-model:value="newProject.assetCategoryId"
                style="width: 100%"
                :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
                placeholder="选择碳资产类型"
                :options="assetsCategories"
              ></a-select>
            </a-form-item>
            <a-form-item label="绿电量">
              <a-input-number v-model:value="newProject.greenElectricityAmount" placeholder="请输入绿电量" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="newProject.certificationStatus">
                <a-select-option value="已认证">已认证</a-select-option>
                <a-select-option value="待认证">待认证</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="详细描述">
              <a-textarea v-model:value="newProject.description" placeholder="请输入详细描述" />
            </a-form-item>
          </a-form>
        </a-modal>

        <div v-if="currentView === 'greenEnergyTrade'">
          <h2>绿电交易</h2>
          <a-table :columns="tradeColumns" :data-source="trades" row-key="key" bordered>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <span>
                  <a @click="showTradeDetails(record.key)">详细信息</a>
                </span>
              </template>
            </template>
          </a-table>
          <a-button type="primary" @click="showAddTradeModal" class="add-trade-button"> 新增交易 </a-button>
        </div>
      </a-card>
    </div>

    <!-- 编辑项目弹窗 -->
    <a-modal title="编辑绿电项目" v-model:visible="isEditProjectModalVisible" @cancel="cancelEditProject" @ok="submitEditProject">
      <a-form :model="currentProject" layout="vertical">
        <a-form-item label="项目名称">
          <a-input v-model:value="currentProject.projectName" placeholder="请输入项目名称" />
        </a-form-item>
        <a-form-item label="碳资产类型">
          <a-select
            v-model:value="currentProject.assetCategoryId"
            style="width: 100%"
            :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
            placeholder="选择碳资产类型"
            :options="assetsCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="绿电量">
          <a-input-number v-model:value="currentProject.greenElectricityAmount" placeholder="请输入绿电量" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="currentProject.certificationStatus">
            <a-select-option value="已认证">已认证</a-select-option>
            <a-select-option value="待认证">待认证</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="详细描述">
          <a-textarea v-model:value="currentProject.description" placeholder="请输入详细描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { message } from 'ant-design-vue';
  import { h, reactive, computed, ref, onMounted } from 'vue';
  import { greenElectricity } from '/@/api/Carbon module/Carbon asset module/Carbon asset project/greenElectricity';
  import { smartSentry } from '/@/lib/smart-sentry';

  const projects = ref([]);

  const tradeColumns = [
    { title: '交易日期', dataIndex: 'date', key: 'date' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '交易量', dataIndex: 'amount', key: 'amount' },
    { title: '交易类型', dataIndex: 'tradeType', key: 'tradeType' },
    { title: '操作', key: 'action' },
  ];

  const trades = ref([{ key: '1', date: '2023-01-01', type: '绿电', amount: '100 MWh', tradeType: '买入' }]);

  const columns = [
    { title: '项目名称', dataIndex: 'projectName', key: 'projectName' },
    { title: '碳资产类型', dataIndex: 'caCategoryName', key: 'caCategoryName' },
    { title: '绿电量', dataIndex: 'greenElectricityAmount', key: 'greenElectricityAmount' },
    { title: '状态', dataIndex: 'certificationStatus', key: 'certificationStatus' },
    { title: '操作', key: 'action' },
  ];

  const newProject = ref({
    projectName: '',
    assetCategoryId: '',
    greenElectricityAmount: null,
    certificationStatus: '',
    description: '',
  });

  const currentProject = ref({ ...newProject.value }); // 用于编辑的项目

  const isAddProjectModalVisible = ref(false);
  const isEditProjectModalVisible = ref(false);
  const currentView = ref('viewProjects');

  const showAddProjectModal = () => {
    newProject.value = {
      projectName: '',
      assetCategoryId: '',
      greenElectricityAmount: null,
      certificationStatus: '',
      description: '',
    };
    isAddProjectModalVisible.value = true;
  };

  const submitNewProject = async () => {
    if (newProject.value.projectName && newProject.value.assetCategoryId && newProject.value.greenElectricityAmount) {
      // 添加新项目
      try {
        await greenElectricity.Add({ ...newProject.value });
        queryData();
      } catch (error) {
        console.log(error);
      }
    } else {
      // 在此处处理表单验证失败的情况
      console.log('请填写所有必需的字段。');
    }
    isAddProjectModalVisible.value = false; // 关闭弹窗
  };
  const cancelAddProject = () => {
    resetNewProjectForm(); // 重置新增项目表单
    currentView.value = 'viewProjects'; // 返回到查看所有项目的视图
  };
  const resetNewProjectForm = () => {
    newProject.value = {
      projectName: '',
      assetCategoryId: '',
      greenElectricityAmount: null,
      certificationStatus: '',
      description: '',
    };
  };

  const editProject = (key) => {
    currentProject.value = { ...key };
    assetsCategories.value.forEach((item) => {
      if (item.caCategoryName == key.caCategoryName) {
        currentProject.value.assetCategoryId = item.caCategoryId;
      }
    });
    console.log(currentProject.value);
    isEditProjectModalVisible.value = true;
  };

  const submitEditProject = async () => {
    if (currentProject.value.projectName && currentProject.value.assetCategoryId && currentProject.value.greenElectricityAmount) {
      // 如果项目存在，则更新该项目
      try {
        await greenElectricity.Update({ ...currentProject.value });
        queryData();
      } catch (error) {
        console.log(error);
      }
    } else {
      // 在此处处理表单验证失败的情况
      console.log('请填写所有必需的字段。');
    }
    isEditProjectModalVisible.value = false; // 关闭弹窗
  };

  const cancelEditProject = () => {
    isEditProjectModalVisible.value = false; // 关闭弹窗
  };

  const deleteProject = async (record) => {
    try {
      await greenElectricity.Delete(record.electricityProjectId);
      queryData();
    } catch (error) {
      console.log(error);
    }
  };

  const showTradeDetails = (key) => {
    // 查看交易详细信息逻辑
  };

  const showAddTradeModal = () => {
    // 添加交易逻辑
  };

  // 查询绿电列表
  const pagination = computed(() => ({
    total: total.value,
    pageSize: queryFormState.pageSize,
    current: queryFormState.pageNum,
    showTotal: (total) => `总共${total}项`,
  }));
  const queryFormState = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const tableLoading = ref(false);
  const total = ref(0); //总数
  const queryForm = reactive({ ...queryFormState });
  async function queryData() {
    tableLoading.value = true;
    try {
      queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
      queryForm.pageSize = queryFormState.pageSize;
      let queryResult = await greenElectricity.query(queryForm);
      projects.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  const handleChange = (pagination, filters, sorter) => {
    queryFormState.pageNum = pagination.current; // 更新当前页
    queryFormState.pageSize = pagination.pageSize; // 更新页大小
    queryData();
  };

  // 碳资产类型
  const assetsCategories = ref([]);
  async function queryAssetsCategory() {
    let queryResult = await greenElectricity.queryAssetsCategory({
      pageNum: 1,
      pageSize: 100,
    });
    assetsCategories.value = queryResult.data.list;
  }

  onMounted(() => {
    queryData();
    queryAssetsCategory();
  });
</script>

<style scoped>
  .green-energy-management {
    display: flex;
  }

  .sidebar {
    width: 240px;
    background-color: white; /* 侧边栏背景色 */
    color: white;
    display: flex;
    flex-direction: column;
    display: table-cell;
    box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  }

  .logo {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
  }

  .main-content {
    flex-grow: 1;
    padding-left: 10px;
    display: table-cell;
  }

  .main-card {
    border-radius: 8px;
  }

  .add-project-button,
  .add-trade-button {
    margin-bottom: 20px; /* 新增项目/交易按钮底部间距 */
  }

  .action-buttons {
    display: flex;
    align-items: center;
  }

  .add-project-button:hover,
  .add-trade-button:hover,
  .edit-button:hover,
  .delete-button:hover {
    opacity: 0.7; /* 悬停效果 */
  }

  .ant-modal-footer {
    display: flex;
    justify-content: flex-end; /* 按钮右对齐 */
  }

  .ant-form-item {
    margin-bottom: 16px; /* 表单项底部间距 */
  }

  .ant-table .ant-table-thead > tr > th {
    background-color: #f0f2f5; /* 表头背景色 */
  }
</style>
